package org.jash.shop2111.login

import android.util.Log
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.launcher.ARouter
import com.hyphenate.chat.ChatClient
import com.hyphenate.helpdesk.callback.Callback
import org.jash.shop2111.databinding.ActivityLoginBinding
import org.jash.shop2111.entry.User
import org.jash.shop2111.mvvm.BaseActivity
import org.jash.shop2111.net.user
import org.jash.shop2111.utils.get
import org.jash.shop2111.utils.put

class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    val userMap by lazy { mutableMapOf<String, String>( "username" to get("username", ""), "password" to get("password", "") ) }

    override fun initData() {
        viewModel.loginLiveData.observe(this, ::login)
    }

    override fun initView() {
        binding.user = userMap
        binding.login.setOnClickListener {
            viewModel.login(userMap)
        }
        binding.username.editText?.addTextChangedListener {
            if((it?.length ?: 0) < 4) {
                binding.username.error = "用户名要大于四位"
                binding.username.isErrorEnabled = true
            } else {
                binding.username.isErrorEnabled = false
            }
        }
    }
    fun login(u: User) {
        user = u
        Log.d("LoginActivity", "login: $u")
        put("username", userMap["username"] ?: "")
        put("password", userMap["password"] ?: "")
        ChatClient.getInstance().login("test02", "test02", object : Callback{
            override fun onSuccess() {
                Log.d("LoginActivity", "onSuccess: ")
            }

            override fun onError(code: Int, error: String?) {
                Log.d("LoginActivity", "onError: $code === $error")
            }

            override fun onProgress(progress: Int, status: String?) {
                Log.d("LoginActivity", "onProgress: $progress === $status")
            }

        })
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
        ARouter.getInstance().build("/shop/main")
            .navigation()
        finish()
    }
}